﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace ImpressionPrint.Utility
{
    public class JsonHelper
    {
        public static string SerializeObject(object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            //这里使用自定义日期格式，如果不使用的话，默认是ISO8601格式           
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd";
            return JsonConvert.SerializeObject(obj, timeConverter);
        }

        /// <summary>
        /// json对象转化为实体对象,转换出错时,返回实例对象，如出错，则记录错误信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string value)
        {
            T obj;

            try
            {
                obj = JsonConvert.DeserializeObject<T>(value);
                return obj;
            }
            catch (Exception ex)
            {
                //LogUtil.Error("DeserializeObject", ex);
            }
            return default(T);
        }

        public static object DeserializeObject(Type type, string value)
        {
            object obj = null;

            try
            {
                obj = JsonConvert.DeserializeObject(value, type);
                return obj;
            }
            catch (Exception ex)
            {
                //LogUtil.Error("DeserializeObject", ex);
            }
            return obj;
        }
    }
}